/*  --------------------------- (C) COPYRIGHT 2021 Fortiortech ShenZhen -----------------------------
    File Name      : Interrupt.c
    Author         : Fortiortech  Appliction Team
    Version        : V1.0
    Editor         : Leo.li
    Date           : 2021-11-05
    Description    : This file contains .C file function used for Motor Control.
    ----------------------------------------------------------------------------------------------------
                                       All Rights Reserved
    ------------------------------------------------------------------------------------------------- */
#include <MyProject.h>

uint16 xdata spidebug[4] = { 0 };
void HardwareInit(void);
void SoftwareInit(void);
/*  -------------------------------------------------------------------------------------------------
    Function Name  : LVW_TSD_INT
    Description    : LVW interrupt，芯片低压预警中断
    Date           : 2021-04-10
    Parameter      : None
    ------------------------------------------------------------------------------------------------- */
void LVW_TSD_INT(void) interrupt 0  //LVW & TSD interrupt
{
    if (ReadBit(LVSR, LVWIF))
    {
        if (ReadBit(LVSR, LVWF))
        {
            mcState = mcFault;
            mcFaultSource = FaultUnderVoltage;
            ClrBit(DRV_CR, FOCEN);  //FOC Disable
            MOE     = 0;
            ClrBit(LVSR, LVWF);
        }
        
        ClrBit(LVSR, LVWIF);
    }
    
    if (TSDIF)
    {
        if (ReadBit(LVSR, TSDF))    //TSDF的作用是用于查询当前温度是否处于过温状态的，可以用于温度降低后恢复启动
        {
            mcFaultSource              = FaultTSD;
            mcState = mcFault;
            ClrBit(LVSR, TSDF);
        }
        
        TSDIF = 0;
    }
}

/*  -------------------------------------------------------------------------------------------------
    Function Name  : FO_INT
    Description    : FO_INT interrupt，需要开启外部中断0，硬件FO过流保护，关断输出，中断优先级最高
    Date           : 2021-04-10
    Parameter      : None
    ------------------------------------------------------------------------------------------------- */
void EXTERN0_INT(void) interrupt 1                  //  外部中断0
{
    if (IF0)
    {
        IF0 = 0;                                // clear P00 interrupt flag
    }
}

/*  -------------------------------------------------------------------------------------------------
    Function Name  : EXTERN_INT
    Description    : 睡眠唤醒
    Date           : 2021-04-10
    Parameter      : None
    ------------------------------------------------------------------------------------------------- */
void EXTERN_INT(void) interrupt 2
{
    if (SleepSet.SleepFlag == 1)
    {
        SleepSet.SleepFlag = 0;
        SleepSet.SleepEn   = 1;
        /*******************Hardware & Software Initial********************/
        HardwareInit();
        SoftwareInit();
    }
    
//    ClrBit(P1_IF, P11);                    // 清零P10标志位
}

/*  -------------------------------------------------------------------------------------------------
    Function Name  : DRV_ISR
    Description    : FOC中断(Drv中断),每个载波周期执行一次，用于处理响应较高的程序，中断优先级第二。DCEN开了就会产生中断。
    Date           : 2021-04-10
    Parameter      : None
    ------------------------------------------------------------------------------------------------- */
void DRV_ISR(void) interrupt 3
{
    if (ReadBit(DRV_SR, FGIF))
    {
        ClrBit(DRV_SR, FGIF);
    }
    
    if (ReadBit(DRV_SR, DCIF))    // 比较中断
    {
			PFCSet.IACTemp = PFC__IAC;
			PFCSet.IACUKTemp = IAC__UK;
			if (mcFocCtrl.Power_Currt < 100)
			{
//				GP07 =~GP07;
			if (PFCSet.IACTemp < 0)
			{
				
				if (PFCSet.IACUKTemp > 2)
				{
					PFCSet.IACUKTemp--;
				}
				else if (PFCSet.IACUKTemp < 0)
				{
					PFCSet.IACUKTemp = 0;
				}
				IAC__UK = PFCSet.IACUKTemp;
			}
		  }
//			if (PFCSet.IACTemp < 0)
//			{
//			GP07 =~GP07;
//			}
			
			   
        FGOutput();
        /* -----软件过流保护----- */
        Fault_Overcurrent();
        TailWindSpeedDetect();
        #if defined (SPI_DBG_SW)            //软件调试模式
        {
            spidebug[0] = IAC__UK;//PFC_CSO;//ADC12_DR;
            spidebug[1] = PFC__IAC;//SOFT_SPIDATA1;
            spidebug[2] = IAC__REF;//SOFT_SPIDATA2;
            spidebug[3] = PFC_CSO;
        }
        #endif
        #if (PFCEnable==1)
        PFCVoltageRespone();
        #endif
        ClrBit(DRV_SR, DCIF);
    }
}

/*---------------------------------------------------------------------------*/
/*  Name     :   void TIM2_INT(void) interrupt 4
    /* Input    :   NO
    /* Output   :   NO
    /* Description: 正反转检测(ISD)
    /*---------------------------------------------------------------------------*/
void TIM2_INT(void) interrupt 4
{
    if (ReadBit(TIM2_CR1, T2IR))
    {
        ClrBit(TIM2_CR1, T2IR);
    }
    
    if (ReadBit(TIM2_CR1, T2IP))
    {
        #if (FRDetectMethod == RSDMethod)
        {
            RSDFRDetect();      //RSD正反转检测
        }
        #endif
        ClrBit(TIM2_CR1, T2IP);
    }
    
    if (ReadBit(TIM2_CR1, T2IF))//溢出中断,用于判断静止,时间为349ms。
    {
        #if (FRDetectMethod == RSDMethod)
        {
            RSDDetect.RSDState = Static;
            RSDDetect.RSDFlag  = 1;
        }
        #endif
        ClrBit(TIM2_CR1, T2IF);
    }
}


/*  -------------------------------------------------------------------------------------------------
    Function Name  : CMP_ISR
    Description    : CMP0/1/2：顺逆风判断
    Date           : 2021-04-10
    Parameter      : None
    ------------------------------------------------------------------------------------------------- */
void CMP_ISR(void) interrupt 7
{
    if (ReadBit(CMP_SR, CMP0IF) || ReadBit(CMP_SR, CMP1IF) || ReadBit(CMP_SR, CMP2IF)) //当检测到比较器中断时
    {
        /* -----通过BEMF做顺逆风检测功能----- */
        BEMFDetectFunc();
        ClrBit(CMP_SR, CMP0IF | CMP1IF | CMP2IF);
    }
}

/*
输入捕获模式: 脉宽检测中断事件标志位
*/
void TIM3_INT(void) interrupt 9
{
    if (ReadBit(TIM3_CR1, T3IR))
    {
        ClrBit(TIM3_CR1, T3IR);
    }
    
    if (ReadBit(TIM3_CR1, T3IP))//周期中断
    {
        if (mcPwmInput.PwmFlag != 1) //若正在计算占空比则不更新
        {
            mcPwmInput.PwmCompare    = TIM3__DR;
            mcPwmInput.PwmArr        = TIM3__ARR;
            mcPwmInput.PwmUpdateFlag = 1;
        }
        
        ClrBit(TIM3_CR1, T3IP);
    }
    
    if (ReadBit(TIM3_CR1, T3IF))
    {
        if (ReadBit(P1, PIN1))//PWM 100%输出
        {
            mcPwmInput.PwmCompare = 8000;
            mcPwmInput.PwmArr     = 8000;
        }
        else//PWM 为0%
        {
            mcPwmInput.PwmCompare = 0;
            mcPwmInput.PwmArr     = 8000;
        }
        
        mcPwmInput.PwmUpdateFlag = 1;
        ClrBit(TIM3_CR1, T3IF);
    }
}

void TIM4_INT(void) interrupt 11
{
    /*TIM4 Interrupt*/
    if (ReadBit(TIM4_CR1, T4IR))
    {
        ClrBit(TIM4_CR1, T4IR);
    }
    
    if (ReadBit(TIM4_CR1, T4IP)) //周期中断
    {
        ClrBit(TIM4_CR1, T4IP);
    }
    
    if (ReadBit(TIM4_CR1, T4IF))
    {
        ClrBit(TIM4_CR1, T4IF);
    }
}

/*  -------------------------------------------------------------------------------------------------
    Function Name  : SYStick_INT
    Description    : 1ms定时器中断（SYS TICK中断），用于处理附加功能，如控制环路响应、各种保护等。中断优先级低于FO中断和FOC中断。
    Date           : 2021-04-10
    Parameter      : None
    ------------------------------------------------------------------------------------------------- */
int16 UDtemp;
int16 UQtemp;

void SYStick_INT(void) interrupt 10
{
    if (ReadBit(DRV_SR, SYSTIF))          // SYS TICK中断
    {
        SetBit(ADC_CR, ADCBSY);           //使能ADC的DCBUS采样

        if ((mcState != mcInit) && (mcState != mcReady))
        {
            /* -----速度滤波----- */
					
            mcFocCtrl.SpeedFlt = LPFFunction(FOC__EOME, mcFocCtrl.SpeedFlt, 100);    //FOC__EOME：估算器估算的速度
            mcFocCtrl.EsValue  = LPFFunction(FOC__EMF << 2, mcFocCtrl.EsValue, 10);	 //FOC__EMF:估算器估算的反电动势
            
            if (mcState == mcRun)
            {
                mcFocCtrl.CurrentPower = FOC__POW << 1;					//FOC__POW电机功率
                /* -----功率滤波----- */
                mcFocCtrl.Powerlpf = LPFFunction(mcFocCtrl.CurrentPower, mcFocCtrl.Powerlpf, 10);
            }
        }
        else
        {
            mcFocCtrl.SpeedFlt = 0;
            mcFocCtrl.Powerlpf = 0;
        }
        
        /*****DCbus的采样获取值并滤波******/
        AdcSampleValue.ADCDcbus = ADC2_DR;  	// ADCDcbus：母线电压	//ADC2_DR:ADC通道2转换结果		//AdcSampleValue:Adc采样值
        mcFocCtrl.mcDcbusFlt = LPFFunction(AdcSampleValue.ADCDcbus, mcFocCtrl.mcDcbusFlt, 100);			//mcDcbusFlt:母线电压
        //        mcFocCtrl.mcDcbusFlt += ((AdcSampleValue.ADCDcbus - mcFocCtrl.mcDcbusFlt) >> 3);
				
				
		AdcSampleValue.ADCIbus = ADC11_DR;		//ADC通道11转换结果
		mcFocCtrl.mcIbusFlt = LPFFunction(AdcSampleValue.ADCIbus, mcFocCtrl.mcIbusFlt, 100);
/*--------------------系统不允许电流超过14.7A------------------------------------------------------*/		
//采集母线电流互感器的电流数据 
//	AdcSampleValue.ADCCTIbus = ADC1_DR;
//				mcFocCtrl.mcCTIbusFlt = LPFFunction(AdcSampleValue.ADCCTIbus, mcFocCtrl.mcCTIbusFlt, 50);
//				AdcSampleValue.ADCCTIbus = ADC1_DR;

		mcFocCtrl.mcCTIbusSum+=((ADC1_DR & 0x7ff8));		//ADC1_DR:ADC通道1转换结果
		mcFocCtrl.mcCTIbusFlt = mcFocCtrl.mcCTIbusSum>>6;	
		mcFocCtrl.mcCTIbusSum -=mcFocCtrl.mcCTIbusFlt;	      
//		mcFocCtrl.mcCTIbusFlt = LPFFunction(AdcSampleValue.ADCCTIbus, mcFocCtrl.mcCTIbusFlt, 50);
		
		#if (Mos_TemperatureProtectEnable)
		{
			mcFocCtrl.MosTempDecFlt = LPFFunction(ADC7_DR, mcFocCtrl.MosTempDecFlt, 10);    // MOS温度检测
		}                    
		#endif
				
/*-------------------------------------------------------------------------------------------------------*/				
				
		if(mcState == mcRun)
		{
			mcFocCtrl.Power_Currt   = (mcFocCtrl.mcIbusFlt  > mcCurOffset.Iw_busOffset)?(mcFocCtrl.mcIbusFlt  - mcCurOffset.Iw_busOffset):(0);
		}
        else 
			{
				mcFocCtrl.Power_Currt = 0;
			}
	
		if (mcFocCtrl.mcDcbusFlt >_Q15(100.0 / HW_BOARD_VOLT_MAX))
			{			 
				GP36 = 1;//继电器
			}
		UDtemp = FOC__UD;
		UQtemp = FOC__UQ;			//q 轴 PI 控制器算出的 q 轴电压
			
        /*****获取调速信号，不同调速模式(PWMMODE,NONEMODE,SREFMODE,KEYSCANMODE)的目标值修改******/
        TargetSpeed_Colletion();			//获取控制的目标值	MotorControl.TargetValue
        /* -----启动ATO控制，环路响应，如速度环、转矩环、功率环等----- */
        Speed_response();	//速度响应函数
        /* -----故障保护函数功能，如过欠压保护、启动保护、缺相、堵转等----- */
        Fault_Detection();	
			
        /*****电机状态机的时序处理*****/
        if (mcFocCtrl.State_Count > 0)
        {
            mcFocCtrl.State_Count--;
        }
		if (Time.PowerOnCnt < 60000)
        {
            Time.PowerOnCnt++;
        }
		if(PFCSet.IacOffsetSamplingDelay > 0)
		{
			PFCSet.IacOffsetSamplingDelay--;
		}
        
        #if ((FRDetectMethod == RSDMethod)&&(TailWind_Mode != NoTailWind))
        {
            if (RSDDetect.RSDCCWSBRCnt > 0)
            {
                RSDDetect.RSDCCWSBRCnt--;
            }
        }
        #endif
        #if ((FRDetectMethod == BEMFMethod)&&(TailWind_Mode != NoTailWind))
        {
            if (BEMFDetect.BEMFTimeCount > 0)
            {
                BEMFDetect.BEMFTimeCount--;
            }
        }
        #endif
        #if ((FRDetectMethod == FOCMethod)&&(TailWind_Mode != NoTailWind))
        {
            FOCTailWindTimeLimit();
        }
        #endif
        #if (PFCPISET==PFCPIMANUAL)
        {
			;
        }
        #elif (PFCPISET==PFCPIAUTO)
        {
            PFCSet.PIParemN = mcFocCtrl.Powerlpf >> 8;
        
            if (PFCSet.PIParemN < 0)
            { PFCSet.PIParemN = 0; }
            else if (PFCSet.PIParemN > 127)
            { PFCSet.PIParemN = 127; }
        
            PFCSet.PFCIKP = CURRENTLOOP_KP[PFCSet.PIParemN] - _Q10(0.20);
            PFCSet.PFCIKI = CURRENTLOOP_KI[PFCSet.PIParemN];
            IAC_KP = PFCSet.PFCIKP;
            IAC_KI = PFCSet.PFCIKI;
        }
        #endif
        #if (PFCEnable)
        PFCRunResponse();
        #endif
        ClrBit(DRV_SR, SYSTIF);                                     // 清零标志位
    }
}
/*  -------------------------------------------------------------------------------------------------
    Function Name  : CMP3_INT
    Description    : CMP3：硬件比较器过流保护，关断输出，中断优先级最高
    Date           : 2021-04-10
    Parameter      : None
    ------------------------------------------------------------------------------------------------- */
void CMP3_INT(void)  interrupt 12
{
    if (ReadBit(CMP_SR, CMP3IF))
    {
        if (mcState != mcPosiCheck)
        {
            FaultProcess();                                                                   // 关闭输出
            mcFaultSource = FaultHardOVCurrent;                                                 // 硬件过流保护
            mcState       = mcFault;                                                          // 状态为mcFault
        }
        
        ClrBit(CMP_SR, CMP3IF);
    }
}
